package com.iwdnb.gkgz.infrastructure.dao.repo.impl;

import java.util.List;
import java.util.Objects;

import com.alibaba.fastjson.JSON;

import com.google.common.collect.Lists;
import com.iwdnb.bmnf.common.service.CacheService;
import com.iwdnb.gkgz.common.constant.CacheConstants;
import com.iwdnb.gkgz.common.model.dto.Stock;
import com.iwdnb.gkgz.infrastructure.dao.repo.StockRepository;
import com.iwdnb.wwzy.dao.MetaDataDAO;
import com.iwdnb.wwzy.model.query.MetaQuery;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.iwdnb.gkgz.common.constant.GkgzConstants.OBJECT_CODE_STOCK;

@Component
public class StockRepositoryImpl implements StockRepository {

    @Autowired
    private MetaDataDAO metaDataDAO;
    @Autowired
    private CacheService cacheService;

    @Override
    public List<Stock> findAll() {
        String cacheKey = CacheConstants.STOCK_LIST_CACHE_KEY;
        String content = cacheService.get(cacheKey);
        if (StringUtils.isNotBlank(content)) {
            return JSON.parseArray(content, Stock.class);
        }
        MetaQuery metaQuery = new MetaQuery();
        List<Stock> stockList = metaDataDAO.queryListByCondition(OBJECT_CODE_STOCK, metaQuery, Stock.class);
        if (CollectionUtils.isNotEmpty(stockList)) {
            content = JSON.toJSONString(stockList);
            cacheService.put(cacheKey, content, 86400);
        }
        return stockList;
    }

    @Override
    public Stock findByCode(String code) {
        if (code.startsWith("sh") || code.startsWith("sz")) {
            code = code.substring(2);
        }
        List<Stock> stockList = findByCodes(Lists.newArrayList(code));
        if (CollectionUtils.isEmpty(stockList)) {
            return null;
        }
        return stockList.get(0);
    }

    @Override
    public List<Stock> findByCodes(List<String> codes) {
        MetaQuery metaQuery = new MetaQuery();
        metaQuery.addParam("codes", codes);
        return metaDataDAO.queryListByCondition(OBJECT_CODE_STOCK, metaQuery, Stock.class);
    }

    @Override
    public void saveAll(List<Stock> stockList) {
        for (Stock stock : stockList) {
            save(stock);
        }
    }

    @Override
    public void save(Stock stock) {
        if (Objects.isNull(stock.getId())) {
            Stock old = findByCode(stock.getCode());
            if (old == null) {
                metaDataDAO.insert(OBJECT_CODE_STOCK, stock);
            } else {
                stock.setId(old.getId());
                metaDataDAO.update(OBJECT_CODE_STOCK, stock);
            }
        } else {
            metaDataDAO.update(OBJECT_CODE_STOCK, stock);
        }
    }

}
